import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'
import { getRoutesApi } from '@/api/index'

export const useMenuStore = defineStore("menu", () => {
	// state :menu
	const menu = reactive(uni.getStorageSync("menu") || {
		workbench: [],
		home: [],
	})

	// actions
	/**
	 获取home路由
	 */
	function getHomeMenu() {
		return new Promise((resolve, reject) => {
			const type = "";
			getRoutesApi(type)
				.then(({ data }) => {
					// console.log('data[0]?.children', data[0]?.children)
					const menuList = resovleMenu(data[0]?.children)
					Object.assign(menu, { ...menu, home:menuList });
					uni.setStorageSync("menu", menu)
					resolve(menuList);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}
	/**
	 处理路由
	 */
	interface MenuProps {
		permissionName:string;
		url:string;
		permissionType:number;
		icon:string;
		enabled:number;
		showType:number;
	}
	function resovleMenu(data: MenuProps[]) {
		const menuList = []
		if (data?.length) {
			data.map ((item: MenuProps)=>{
				// console.log('resovleMenu', item)

				if (item.permissionType === 1) {
					menuList.push({
						name: item.permissionName,
						url: item.url,
						icon: item.icon || 'api',
						enabled: item.enabled,
						hidden: item.showType === 2? true: false
					})
				}
			})
		}
		return menuList
	}
	return { menu, getHomeMenu }
})